package com.xinzhidi.web.netty.utils;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.xinzhidi.common.constant.CacheConstants;
import com.xinzhidi.common.constant.HttpStatus;
import com.xinzhidi.common.core.domain.model.LoginUser;
import com.xinzhidi.common.core.redis.RedisCache;
import com.xinzhidi.common.exception.ServiceException;
import com.xinzhidi.common.utils.SecurityUtils;
import com.xinzhidi.common.utils.StringUtils;
import com.xinzhidi.common.utils.spring.SpringUtils;
import com.xinzhidi.system.service.IUserPlotService;
import com.xinzhidi.web.plot.domain.entity.CPlot;
import com.xinzhidi.web.plot.service.impl.CPlotServiceImpl;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 安全服务工具类
 *
 * @author ruoyi
 */
public class SecurityAdminUtils {

    /**
     * 获取用户管辖小区
     **/
    public static List<Long> getUserPlotIds() {
        try {
            LoginUser loginUser = SecurityUtils.getLoginUser();
            RedisCache redisCache = SpringUtils.getBean(RedisCache.class);
            String key = loginUser.getUserId() + CacheConstants.LOGIN_USER_PLOT_IDS;
            List<Long> plotIds = redisCache.getCacheList(key);
            if (CollectionUtils.isEmpty(plotIds)){
                List<CPlot> plots;
                IUserPlotService userPlotService = SpringUtils.getBean(IUserPlotService.class);
                CPlotServiceImpl plotService = SpringUtils.getBean(CPlotServiceImpl.class);

                if (StringUtils.isNotNull(loginUser.getUserId()) && isAdmin(loginUser.getUserId())) {
                    plotIds = plotService.list().stream().map(CPlot::getId).collect(Collectors.toList());
                }else{
                    plotIds = userPlotService.getPlotIdsByUserId(loginUser.getUserId());
                }
                if (CollectionUtils.isNotEmpty(plotIds)){
                    redisCache.setCacheList(key,plotIds);
                }
            }
            return plotIds;
        } catch (Exception e) {
            throw new ServiceException("获取用户小区权限异常", HttpStatus.UNAUTHORIZED);
        }
    }

    /**
     * 是否为管理员
     *
     * @param userId 用户ID
     * @return 结果
     */
    public static boolean isAdmin(Long userId) {
        return userId != null && 1L == userId;
    }
}
